package com.um.jdy.platform.user.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.um.jdy.common.platform.dao.CompanyUserDao;
import com.um.jdy.common.platform.entity.po.CompanyUser;
import com.um.jdy.platform.user.service.SessionUserService;
import com.um.springboot.starter.constants.Constants;
import com.um.springboot.starter.helper.SessionHelper;
import com.um.springboot.starter.properties.HshProperties;
import com.um.springboot.starter.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author 邓南辉
 * 日期 2023/6/1
 * 版权所有 广州优匠科技有限公司
 */
@Service
@Transactional
@Slf4j
public class SessionUserServiceImpl implements SessionUserService {

    @Resource
    private HttpServletRequest request;

    @Autowired
    CompanyUserDao companyUserDao;

    @Autowired
    HshProperties hshProperties;

    @Autowired
    SessionHelper sessionHelper;

    @Override
    public CompanyUser getTokenUser() {
        CompanyUser user = null;
        if ("token".equals(hshProperties.getConfig().getSessionType())) {
            String token = request.getHeader("token");
            if (StrUtil.isNotBlank(token)) {
                user = companyUserDao.getEntityBySqlName("get_platform_user_by_token", token);
            }
        } else if ("sa-token".equals(hshProperties.getConfig().getSessionType())) {
            String userId = StpUtil.getLoginId(null);
            if (StrUtil.isNotBlank(userId)) {
                user = companyUserDao.getEntity(userId);
            }
        } else {
            user = (CompanyUser) sessionHelper.getAttribute(Constants.SESSION_USER);
        }
        return user;
    }


    @Override
    public String getTokenUserId() {
        CompanyUser user = this.getTokenUser();
        if (null == user) {
            return "";
        }
        return StringUtil.getTrim(user.getPlatformCompanyUserId());
    }



}
